"""
第一阶段处理器 (Stage 1 Processor)
AIDA框架第一阶段：解构与标准化
整合文件接收、智能解析、内容分类和存储管理
"""

import os
from typing import Dict, Any, List, Optional
from loguru import logger
from pathlib import Path

from .file_ingestor import FileIngestor
from .intelligent_parser import IntelligentParser
from .content_classifier import ContentClassifier, ClassifiedElement
from .storage_manager import StorageManager


class Stage1Processor:
    """第一阶段处理器类"""
    
    def __init__(self, storage_base_path: str = "storage"):
        """
        初始化第一阶段处理器
        
        Args:
            storage_base_path: 存储基础路径
        """
        self.file_ingestor = FileIngestor()
        self.intelligent_parser = IntelligentParser()
        self.content_classifier = ContentClassifier()
        self.storage_manager = StorageManager(storage_base_path)
        
        logger.info("AIDA框架第一阶段处理器初始化完成")
    
    def process_pdf(self, file_path: str, show_details: bool = True) -> Dict[str, Any]:
        """
        处理PDF文件的完整流程
        
        Args:
            file_path: PDF文件路径
            show_details: 是否显示详细的解析过程
            
        Returns:
            处理结果字典
        """
        logger.info(f"开始处理PDF文件: {file_path}")
        
        try:
            # 第1步：文件接收和验证
            logger.info("步骤1: 文件接收和验证")
            validation_result = self.file_ingestor.ingest_file(file_path)
            
            if not validation_result["is_valid"]:
                error_msg = f"文件验证失败: {validation_result['error']}"
                logger.error(error_msg)
                return {
                    "success": False,
                    "error": error_msg,
                    "stage": "file_validation"
                }
            
            logger.info(f"文件验证通过: {validation_result['file_info']}")
            
            # 第2步：智能解析
            logger.info("步骤2: 智能解析PDF内容")
            parsed_elements = self.intelligent_parser.parse_pdf(file_path)
            logger.info(f"解析完成，提取到 {len(parsed_elements)} 个文档元素")
            
            if show_details:
                self._show_parsing_details(parsed_elements)
            
            # 第3步：内容分类
            logger.info("步骤3: 内容分类和标准化")
            classified_elements = self.content_classifier.classify_elements(parsed_elements)
            logger.info(f"分类完成，处理了 {len(classified_elements)} 个元素")
            
            if show_details:
                self._show_classification_details(classified_elements)
            
            # 第4步：按三级标题分组
            logger.info("步骤4: 按三级标题分组")
            level3_groups = self.content_classifier.group_by_level3_titles(classified_elements)
            logger.info(f"分组完成，共 {len(level3_groups)} 个三级标题组")
            
            if show_details:
                self._show_grouping_details(level3_groups)
            
            # 第5步：结构化存储
            logger.info("步骤5: 结构化存储")
            storage_result = self.storage_manager.store_classified_elements(
                classified_elements, level3_groups, file_path
            )
            logger.info(f"存储完成，会话ID: {storage_result['session_id']}")
            
            # 第6步：生成分类统计
            classification_summary = self.content_classifier.get_classification_summary(classified_elements)
            
            # 组装最终结果
            result = {
                "success": True,
                "session_id": storage_result["session_id"],
                "storage_path": storage_result["storage_path"],
                "file_info": validation_result["file_info"],
                "parsing_summary": {
                    "total_elements": len(parsed_elements),
                    "element_types": self._get_element_type_distribution(parsed_elements)
                },
                "classification_summary": classification_summary,
                "level3_groups": {
                    "count": len(level3_groups),
                    "groups": list(level3_groups.keys())
                },
                "storage_summary": storage_result["statistics"],
                "stored_files": storage_result["stored_files"]
            }
            
            logger.info("第一阶段处理完成")
            return result
            
        except Exception as e:
            error_msg = f"处理过程中发生错误: {str(e)}"
            logger.error(error_msg)
            return {
                "success": False,
                "error": error_msg,
                "stage": "processing"
            }
    
    def _show_parsing_details(self, parsed_elements: List[Dict[str, Any]]):
        """
        显示解析详情
        
        Args:
            parsed_elements: 解析后的元素列表
        """
        logger.info("=== 解析详情 ===")
        
        # 按类型统计
        type_counts = {}
        for element in parsed_elements:
            element_type = element.get("element_type", "unknown")
            if element_type not in type_counts:
                type_counts[element_type] = 0
            type_counts[element_type] += 1
        
        logger.info("元素类型分布:")
        for element_type, count in type_counts.items():
            logger.info(f"  {element_type}: {count} 个")
        
        # 显示前几个元素的示例
        logger.info("前5个元素示例:")
        for i, element in enumerate(parsed_elements[:5]):
            content_preview = element.get("content", "")[:100] + "..." if len(element.get("content", "")) > 100 else element.get("content", "")
            logger.info(f"  [{i+1}] {element.get('element_type', 'unknown')}: {content_preview}")
    
    def _show_classification_details(self, classified_elements: List[ClassifiedElement]):
        """
        显示分类详情
        
        Args:
            classified_elements: 分类后的元素列表
        """
        logger.info("=== 分类详情 ===")
        
        # 按类别统计
        category_counts = {}
        subcategory_counts = {}
        
        for element in classified_elements:
            # 类别统计
            if element.category not in category_counts:
                category_counts[element.category] = 0
            category_counts[element.category] += 1
            
            # 子类别统计
            subcategory_key = f"{element.category}.{element.subcategory}"
            if subcategory_key not in subcategory_counts:
                subcategory_counts[subcategory_key] = 0
            subcategory_counts[subcategory_key] += 1
        
        logger.info("类别分布:")
        for category, count in category_counts.items():
            logger.info(f"  {category}: {count} 个")
        
        logger.info("子类别分布:")
        for subcategory, count in subcategory_counts.items():
            logger.info(f"  {subcategory}: {count} 个")
        
        # 显示三级标题示例
        level3_titles = [e for e in classified_elements if e.subcategory == "level3_title"]
        if level3_titles:
            logger.info(f"发现 {len(level3_titles)} 个三级标题:")
            for title in level3_titles[:10]:  # 显示前10个
                level3_number = title.metadata.get("level3_number", "")
                logger.info(f"  {level3_number}: {title.content[:50]}...")
    
    def _show_grouping_details(self, level3_groups: Dict[str, List[ClassifiedElement]]):
        """
        显示分组详情
        
        Args:
            level3_groups: 三级标题分组
        """
        logger.info("=== 三级标题分组详情 ===")
        
        for level3_number, elements in level3_groups.items():
            logger.info(f"组 {level3_number}: {len(elements)} 个元素")
            
            # 统计组内元素类型
            type_counts = {}
            for element in elements:
                element_type = element.category
                if element_type not in type_counts:
                    type_counts[element_type] = 0
                type_counts[element_type] += 1
            
            type_summary = ", ".join([f"{t}:{c}" for t, c in type_counts.items()])
            logger.info(f"  类型分布: {type_summary}")
    
    def _get_element_type_distribution(self, parsed_elements: List[Dict[str, Any]]) -> Dict[str, int]:
        """
        获取元素类型分布
        
        Args:
            parsed_elements: 解析后的元素列表
            
        Returns:
            类型分布字典
        """
        distribution = {}
        for element in parsed_elements:
            element_type = element.get("element_type", "unknown")
            if element_type not in distribution:
                distribution[element_type] = 0
            distribution[element_type] += 1
        
        return distribution
    
    def get_session_info(self) -> Dict[str, str]:
        """
        获取当前会话信息
        
        Returns:
            会话信息字典
        """
        return {
            "session_id": self.storage_manager.get_session_id(),
            "storage_path": self.storage_manager.get_session_path()
        }